package com.zxmr.utility.audit;

import java.util.Calendar;
import java.util.List;

import com.zxmr.asyn.TaskMonitor;
import com.zxmr.audit.Audit;
import com.zxmr.audit.AuditScheduleCallBack;
import com.zxmr.domain.service.TaskService;
import com.zxmr.util.Utils;

public class TaskStateAudit extends Audit{

	long oneDay = 24*60*60*1000;
	Calendar cal;
	TaskStateAudit next;
	TaskMonitor monitor;
	public TaskStateAudit(Calendar cal,TaskMonitor monitor)
	{
		this.cal = cal;  
		this.monitor = monitor;
	}
	@Override
	public void audit() {
		
		String currentTime = Utils.getCurrentTime();
		
		TaskService service = new TaskService();
		List<Long> expiredTasks = service.queryExpiredTask(currentTime);
		
		service.updateExiredTask(currentTime);
		service.expired(expiredTasks);
		
		System.out.println("going to schedule next audit");
		// schedule next audit;
		AuditScheduleCallBack callback = new AuditScheduleCallBack(next);
		long nextTime = next.getAuditTime();
		if(nextTime < 0)
		{
			nextTime += oneDay;
		}
		monitor.addTask(callback, nextTime);
	}
	public long getAuditTime()
	{
		int today = Calendar.getInstance().get(Calendar.DATE);
		cal.set(Calendar.DATE, today);
		long timeout = Utils.timeFromNow(cal.getTime());
		return timeout;
	}
	public void setNextAudit(TaskStateAudit next)
	{
		this.next = next;
	}
	public void setCalendar(Calendar cal)
	{
		this.cal = cal;
	}
	public Calendar getCalendar()
	{
		return this.cal;
	}

}
